var gulp = require('gulp'),
    pug = require('gulp-pug'),
    htmlBeautify = require('gulp-html-beautify'),
    htmlmin = require('gulp-htmlmin'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    scsslint = require('gulp-scss-lint'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    del = require('del'),
    gutil = require('gulp-util'),
    plumber = require('gulp-plumber'),    //错误管理
    browserSync = require('browser-sync').create(),      // 浏览器同步
    reload = browserSync.reload;                // 自动刷新

gulp.task('serve',['sass'], function() {

    browserSync.init({
        server: {
            baseDir: "dist/assets"
        }
    });

    // gulp.watch("dist/assets/css/*.css", ['sass']);
    gulp.watch("dist/assets/*.html").on('change', reload);
});

gulp.task('lint', function() {
    gulp.src('js/main.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(gulp.dest('dist/assets/js'));
});

gulp.task('sass', function() {
  return gulp.src('css/*.scss')
    .pipe(plumber()) 
    .pipe(sass())
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(autoprefixer({
        browsers: ['last 5 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4', 'Firefox ESR'],
        cascade: true, 
        remove: false
    }))
    .pipe(scsslint())
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(notify({ message: 'Styles task complete' }))
    .pipe(reload({stream: true}));
});   

gulp.task('pug', function() {
    return gulp.src(['pug/*.pug', 'pug/**/*.pug'])
        .pipe(plumber()) 
        .pipe(pug({
            pretty: true
        }))
        .pipe(htmlBeautify({
            indent_size: 4,
            indent_char: ' ',
            // 这里是关键，可以让一个标签独占一行
            unformatted: true,
            // 默认情况下，body | head 标签前会有一行空格
            extra_liners: []
        }))
        // 最后使用 htmlmin 来统一输出的 html 格式
        .pipe(htmlmin({
        }))
        .pipe(gulp.dest('dist/assets'))
})

gulp.task('watch', function () {
    gulp.watch(['pug/*.pug', 'pug/**/*.pug', 'css/*.scss', 'js/main.js'], ['pug', 'sass', 'lint']);
});

gulp.task('default', ['pug', 'sass', 'lint', 'watch', 'serve']);

gulp.task('clean', function(cb) {
    del(['dist/assets/css', 'dist/assets/js'], cb)
});

